package com.SalaryWorksPro.util;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import javax.swing.*;
import javax.swing.table.TableModel;
import java.io.FileOutputStream;
import java.io.IOException;
 
public class SwingTableToExcelExporter {
    public static void exportToExcel(JTable table, String filePath) throws IOException {
        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("Sheet1");
 
        // 获取表格模型
        TableModel tableModel = table.getModel();
 
        // 创建表头行
        Row headerRow = sheet.createRow(0);
        for (int col = 0; col < tableModel.getColumnCount(); col++) {
            Cell cell = headerRow.createCell(col);
            cell.setCellValue(tableModel.getColumnName(col));
        }
 
        // 填充数据行
        for (int row = 0; row < tableModel.getRowCount(); row++) {
            Row dataRow = sheet.createRow(row + 1);
            for (int col = 0; col < tableModel.getColumnCount(); col++) {
                Cell cell = dataRow.createCell(col);
                Object cellValue = tableModel.getValueAt(row, col);
                if (cellValue != null) {
                    cell.setCellValue(cellValue.toString());
                }
            }
        }
 
        try (FileOutputStream fileOut = new FileOutputStream(filePath)) {
            workbook.write(fileOut);
        }
 
        workbook.close();
    }
 
    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                JTable table = new JTable();
 
                // 添加表格数据
 
                String filePath = "C:/path/to/output.xlsx";
 
                try {
                    exportToExcel(table, filePath);
                    JOptionPane.showMessageDialog(null, "导出成功！");
                } catch (IOException e) {
                    JOptionPane.showMessageDialog(null, "导出失败：" + e.getMessage());
                }
            }
        });
    }
}